﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESoft.AspNetCore.DTO;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;

namespace ESoft.AspNetCore.Authentication
{
    /// <summary>
    /// HeaderAuthorizeAttribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class HeaderAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="configuration"></param>
        public HeaderAuthorizeAttribute(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// OnAuthorization
        /// </summary>
        /// <param name="filterContext"></param>
        public virtual void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            var authenticate =
                filterContext.HttpContext.AuthenticateAsync(HeaderAuthenticationDefaults.AuthenticationSchema);

            if (authenticate.Result.Succeeded || this.SkipUserAuthorize(filterContext.ActionDescriptor))
            {
                return;
            }

            filterContext.Result =
                new JsonResult(ResponseResult.FailOut(ResponseResult.LOGIN_TIME_OUT, new Exception("登陆信息已过期，请重新登录！")));
        }

        protected virtual bool SkipUserAuthorize(ActionDescriptor actionDescriptor)
        {
            bool skipAuthorize = actionDescriptor.FilterDescriptors.Any(a =>
                a.Filter is AllowAnonymousFilter);
            return skipAuthorize;
        }
    }
}
